package cn.baiweigang.uu.service.okhttp;

import cn.baiweigang.uu.utils.LogUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class HttpService {

    private OkHttpClient httpClient;

    @PostConstruct
    private void init(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectionPool(new ConnectionPool(200, 10, TimeUnit.SECONDS)).connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS);
        httpClient = builder.build();
    }


    public String doGet(String url, Map<String, String> header, Map<String, String> params) {
        Request.Builder reqBuild = new Request.Builder();

        //设置url和参数
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if (MapUtils.isNotEmpty(params)) {
            params.forEach((k, v) -> {
                urlBuilder.addQueryParameter(k, v);
            });
        }
        reqBuild.url(urlBuilder.build());

        //设置header
        if (MapUtils.isNotEmpty(header)){
            header.forEach((k, v) -> {
                reqBuild.addHeader(k,v);
            });
        }

        Response response = null;
        try {
            response = httpClient.newCall(reqBuild.build()).execute();
        } catch (IOException e) {
            LogUtil.logError("http执行异常，url=" + url);
            LogUtil.logError(e.getMessage());
            return null;
        }

        if (response.isSuccessful()) {
            try {
                return response.body().string();
            } catch (IOException e) {
                LogUtil.logError("http结果解析异常" + url);
                LogUtil.logError(e.getMessage());
            }
        } else {
            int statusCode = response.code();
            LogUtil.logError("响应码不为200，返回响应码：" + statusCode + "，url：" + urlBuilder.build());
        }
        return null;
    }

    public String doPost(String uri, Map<String, String> header, JSONObject json) {
        try {
            RequestBody body = RequestBody.create(MediaType.parse("application/json"),json.toJSONString());
            Request.Builder reqBuild = new Request.Builder().url(uri).post(body);
            //设置header
            if (MapUtils.isNotEmpty(header)){
                header.forEach((k, v) -> {
                    reqBuild.addHeader(k,v);
                });
            }
            Request request = reqBuild.build();
            Response response = httpClient.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            LogUtil.logError("IOException 目标url：" + uri);
            LogUtil.logError(e.getMessage());
        }
        return null;
    }
}
